package com.dayuanit.chat;

import java.io.*;
import java.net.Socket;

public class Client2 {
    private static final String serverIP = "192.168.5.112";
    private static final int sreverPort = 9999;

    private static Socket socket;

    static {
        try {
            socket = new Socket(serverIP, sreverPort);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取键盘输入的信息
    public static void readKeyBoard() throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        String msg = null;
        //读取键盘输入的信息
        while (null != (msg = br.readLine())) {
            bufferedWriter.write(msg);
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
    }

    //接收服务器端发送的消息
    public static void receiveMsgFromServer() throws Exception {
        System.out.println("------------------接收服务器的消息2...---------------------");
        //客户端接收服务器端发过来的消息
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String msg = null;
        while (null != (msg = bufferedReader.readLine())) {
            System.out.println("接收到服务器的消息2:->" + msg);
        }
    }

    public static void main(String[] args) throws Exception {
        //客户端 也就是聊天的用户

        //由于客户端既要读取键盘的输入，又要读取服务器端的信息，两者是并行的，不是串行的，所以，要开启两个线程
        //来负责执行这两个方法。
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    readKeyBoard();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "readKeyBoardThread").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    receiveMsgFromServer();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"receiveServerMsgThread").start();

    }
}
